package at.fhj.itm.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import at.fhj.itm.dao.GenericDao;
import at.fhj.itm.model.Player;


public class MySQLDao implements GenericDao {

	private Connection con;
	private static MySQLDao Instance;

	private MySQLDao()
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static MySQLDao getInstance(){
		
		if(Instance==null){
			Instance = new MySQLDao();
		}
		return Instance;
		
	}
	
	public boolean connect() {
		
		try {
			con = DriverManager.getConnection("jdbc:mysql://localhost/itm08_lukas_gruber_bac2", "root", "");
		}
		catch(SQLException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	public void disconnect() {
		try {
			con.close();
		}
		catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isConnected() {
		try {
			if(con != null && !con.isClosed()) {
				return true;
			}
		}
		catch(SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}

	public void save(Player player) {
		try {
			Statement st = con.createStatement();
			
			StringBuilder sb = new StringBuilder();
			sb.append("INSERT INTO quiz VALUES (");
			sb.append("DEFAULT, '");
			sb.append(player.getName()).append("', ");
			sb.append(player.getScore());
			sb.append(")");
			
			st.execute(sb.toString());
		}
		catch(SQLException e) {
			e.printStackTrace();
		}
	}

	public List<Player> findAll() {
		List<Player> players = new ArrayList<Player>();
		try {
			Statement st = con.createStatement();
			
			ResultSet rs = st.executeQuery("SELECT * FROM quiz");
			
			while(rs.next()) {
				players.add(new Player(rs.getString("name"), rs.getInt("score")));
			}
		}
		catch(SQLException e) {
			e.printStackTrace();
		}
		
		return players;
	}

}
